﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using dbo;
using LitJson;
using System.Net.Http;
using System.IO;
using System.Data;
namespace NewFarm
{

    class User:IDisposable
    {
        public Socket socket;
        public int id;
        public string Pid;
        private Queue<string> _msg_queue;
        public User(Socket _socket)
        {
            _msg_queue = new Queue<string>();
            socket = _socket;
            byte[] buffer = new byte[1024*16];
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), buffer);
        }
        
        public void Dispose()
        {
            try
            {
                LogInController.instance.ChangeWithLock(false);
                Console.WriteLine("****************Disposed Ip Is:" + socket.RemoteEndPoint + "*******************");
                GC.Collect(2, GCCollectionMode.Forced);
                socket.Close();
            }
            catch (Exception e)
            {
                System.Threading.Thread.CurrentThread.Abort();
                Console.WriteLine(socket);
                Console.WriteLine("!!!!!!!!!!!!!!!!!Occured Exception When Disposing!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                Console.WriteLine("*****$exception begin$******");
                Console.WriteLine("ErrorTime:" + DateTime.Now);
                Console.WriteLine("ErrorMessage:" + e.Message);
                Console.WriteLine("ErrorStackTrace:" + e.StackTrace);
                Console.WriteLine("ErrorTargetSite:" + e.TargetSite);
                Console.WriteLine("ErrorSource:" + e.Source);
                Console.WriteLine("*****$exception end$******");
            }
        }
        void  RecieveCallBack(IAsyncResult ir)
        {
            try 
            {
                int length = socket.EndReceive(ir);
                byte[] Orig = (byte[])ir.AsyncState;
                byte[] buff = new byte[length];
                for (int i = 0; i < length; i++)
                {
                    buff[i] = Orig[i];
                }
                string req = Encoding.UTF8.GetString(buff);
                if (req != "")
                {
                    
                        HandleClientReq(req);
                        Orig=new byte[1024*16];
                        socket.BeginReceive(Orig,0, Orig.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), Orig);
                }
                else 
                {
                    Dispose();
                    Console.WriteLine("!!!!!!!!!!!!!!Disposed With Empty String!!!!!!!!!!!!!!!!!");
                } 
            }
            catch(Exception  e)
            {
                Dispose();
                Console.WriteLine("!!!!!!!!!!!!!!Disposed With Socket Exception!!!!!!!!!!!!!!!!!" );
            }
        }
        void   HandleClientReq(string msg)
        {
           Console.WriteLine(msg);
           try
            {
               string Response = "empty";
               JsonData jd = null;
               try
               {
                   jd = JsonMapper.ToObject(msg);
               }
               catch
               {
                   Dispose();
                   Console.WriteLine("!!!!!!!!!!!!!!!!!Disposed With UnCompetable Data!!!!!!!!!!!!!" );
                   return;
               }
               int type = (int)jd["type"];
               SQLEnum EnumType = (SQLEnum)type;
               switch (EnumType)
               {
                   case SQLEnum.数据同步:
                       Response = LogIn(jd["msg"], type);
                       CheckUnConfirmedAppleData(jd["AppleData"]);
                       break;
                   case SQLEnum.Reconnect:
                       Response = LogInDuringTheGame(jd["msg"], jd["CurrentReq"], type);
                       CheckUnConfirmedAppleData(jd["AppleData"]);
                       break;
                   case SQLEnum.进入选关场景:
                       Response = EnterChooseLevelScene(type);
                       break;
                   case SQLEnum.准备进入游戏:
                       Response = ReadyToEnterGame((int)jd["msg"], type);
                       break;
                   case SQLEnum.进入大关选择界面:
                       Response = EnterChooseBigLevelUI(type);
                       break;
                   case SQLEnum.通过关卡:
                       Response = GameSuccessGetRank((int)jd["msg"], type);
                       break;
                   case SQLEnum.关卡失败:
                       Response = GameFailGetRank((int)jd["msg"], type);
                       break;
                   case SQLEnum.更新胜利关卡信息:
                       Response = PassLevelSuccessful(jd["msg"], type);
                       break;
                   case SQLEnum.更新失败关卡信息:
                       Response = PassLevelFail(jd["msg"], type);
                       break;
                   case SQLEnum.响应活动和首次充值按钮界面:
                       Response = GetCurrentActivity(type);
                       break;
                   case SQLEnum.活动奖励排名界面:
                       Response = ActivityRewardRankUI(type);
                       break;
                   case SQLEnum.进入活动奖励界面:
                       Response = GetCurrentActivity(type);
                       break;
                   case SQLEnum.打开商店界面UI:
                       Response = OpenStoreUI(type);
                       break;
                   case SQLEnum.更多商品:
                       Response = OpenMoreStoreUI(type);
                       break;
                   case SQLEnum.购买了一个商品:
                      BuyedOneProduct(jd["msg"]);
                       return;
                   case SQLEnum.打开体力界面UI:
                       Response = OpenPowerUI(type);
                       break;
                   case SQLEnum.用货币购买道具体力:
                       Response = BuyPowerUI(type);
                       break;
                   case SQLEnum.打开购买道具界面:
                       Response = GetItemCostList((int)jd["msg"], type);
                       break;
                   case SQLEnum.购买了一个道具:
                       Response = BuyOneItem(jd["msg"], type);
                       break;
                   case SQLEnum.游戏失败是否继续游戏界面:
                       Response = GameFailToContinueUI(type);
                       break;
                   case SQLEnum.打开好友消息界面:
                       Response = OpenMsgUI(type);
                       break;
                   case SQLEnum.打开任务列表界面:
                       Response = GetMissionList(type);
                       break;
                   case SQLEnum.打开地图选择界面:
                       Response = ChooseMapUI(type);
                       break;
                   case SQLEnum.打开每日奖励界面:
                       Response = GetDailyRewardUI(type);
                       break;
                   case SQLEnum.新的好友消息:
                       Response = NewFriendMsg(type);
                       break;
                   case SQLEnum.打开游戏中的设置界面:
                       Response = OpenSettingsInGame(type);
                       break;
                   case SQLEnum.接受一个好友赠送的体力:
                       Response = RecieveFriendDonatedPower(jd["msg"], type);
                       break;
                   case SQLEnum.赠送好友体力:
                       Response = DonatePowerToFriends(type);
                       break;
                   case SQLEnum.完成一个任务:
                       Response = GetMissionReward(jd["msg"], type);
                       break;
                   case SQLEnum.领取今日奖励:
                       Response = GetDailyReward(type,(int)jd["msg"]);
                       break;
                   case SQLEnum.退出游戏确认界面:
                       Response = ExitGameConfirmUI(type);
                       break;
                   case SQLEnum.刷新道具数量:
                       Response = RefreshItemCount(type);
                       break;
                   case SQLEnum.体力扣除:
                       Response = ReducePower(type);
                       break;
                   case SQLEnum.进入首次充值界面:
                       Response = FuckingFunc(type);
                       break;
                   case SQLEnum.使用道具:
                       Response = UseItem((int)jd["msg"], type);
                       break;
                   case SQLEnum.消耗金币:
                       Response = UseGold(jd["msg"], type);
                       break;
                   case SQLEnum.连接FackBook:
                       Response = LogInWithFaceBookId(jd["msg"], type);
                       break;
                   case SQLEnum.首次充值购买按钮点击:
                       BuyActivityBuyOp(jd["msg"]);
                       return;
                   case SQLEnum.ggn:
                       Response = GetGameCenterName((string)jd["msg"],type);
                       break;
                   case SQLEnum.seg:
                       Exc_SEG((int)jd["msg"]);
                       return;
                   case SQLEnum.config:
                       Exc_Config((int)jd["msg"],(int)jd["ReqId"]);
                       return;
                   case SQLEnum.ads:
                       UpDateWatchAdsCount(jd["msg"]);
                       return;
               }
               byte[] buffer = Encoding.UTF8.GetBytes(Response);
               socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (IAsyncResult ir) => { }, null);
               //Console.WriteLine("Response From Server:" + Response);
           }
           catch (Exception e)
           {
               Dispose();
               Console.WriteLine("!!!!!!!!Disposed When Handling The Recieved Data!!!!!!!!!!!!" );
               Console.WriteLine("*****$exception begin$******");
               Console.WriteLine("ErrorTime:" + DateTime.Now);
               Console.WriteLine("ErrorMessage:" + e.Message);
               Console.WriteLine("ErrorStackTrace:" + e.StackTrace);
               Console.WriteLine("ErrorTargetSite:" + e.TargetSite);
               Console.WriteLine("ErrorSource:"+e.Source);
               Console.WriteLine("*****$exception end$******");
           }
        }
        void   UpDateWatchAdsCount(JsonData jd)
        {
          int CurrentLevel=(int)jd["CurrentLevel"];
          if(CurrentLevel>1000)
          {
              CurrentLevel -= 1000;
          }
          int AdsType=(int)jd["AddsType"];
          DataRowCollection drc = DBManager.Select("select LevelWatchAdsInfo from info");
          JsonData AdsData = JsonMapper.ToObject((string)drc[0][0]);
          JsonData FailToContinueAds = AdsData["FailToContinueAds"];
          int DailyRewardUIAds = (int)AdsData["DailyRewardUIAds"];
          int count = (int)FailToContinueAds[CurrentLevel - 1];
          if (AdsType == 0)
          {
              DailyRewardUIAds += 1;
              AdsData["DailyRewardUIAds"] = DailyRewardUIAds;
          }
          else if(AdsType==1)
          {
              count += 1;
              FailToContinueAds[CurrentLevel - 1] = count;
          }
          DBManager.Update(string.Format("update info set LevelWatchAdsInfo='{0}'", AdsData.ToJson()));
        }
        void   BuyedOneProduct(JsonData  dt)
        {
            int DataId = (int)dt["DataId"];
            int ReqId = (int)SQLEnum.购买了一个商品;
            string AppleData = (string)dt["AppleData"];
            string version = (string)dt["Version"];
            object[] objs = new object[6];
            objs[0] = socket;
            objs[1] = this.id;
            objs[2] = AppleData;
            objs[3] = ReqId;
            objs[4] = DataId;
            objs[5] = version;
            DBManager.Insert(string.Format("insert into fromclient (Id,DataFromClient,DataId,ReqId) values ({0},'{1}',{2},{3})", this.id, AppleData, DataId, ReqId));
            LogInController.instance.UsersToValidateData.Enqueue(objs);
        }
        void   BuyActivityBuyOp(JsonData dt) //充值活动的充值操作
        {
            int DataId = (int)dt["DataId"];
            int ReqId = (int)SQLEnum.首次充值购买按钮点击;
            string AppleData = (string)dt["AppleData"];
            string version = (string)dt["Version"];
            object[] objs = new object[6];
            objs[0] = socket;
            objs[1] = this.id;
            objs[2] = AppleData;
            objs[3] = ReqId;
            objs[4] = DataId;
            objs[5] = version;
            DBManager.Insert(string.Format("insert into fromclient (Id,DataFromClient,DataId,ReqId) values ({0},'{1}',{2},{3})", this.id, AppleData, DataId, ReqId));
            LogInController.instance.UsersToValidateData.Enqueue(objs);
        }
        void   CheckUnConfirmedAppleData(JsonData ValidateData)
        {
            int DataId = (int)ValidateData["DataId"];
            if(DataId==-1)
            {
                return;
            }
            int ReqId = (int)ValidateData["ReqId"];
            string AppleData = (string)ValidateData["AppleData"];
            string version = (string)ValidateData["Version"];
            SQLEnum type = (SQLEnum)ReqId;
            object[] objs = new object[6];
            objs[0] = socket;
            objs[1] = this.id;
            objs[2] = AppleData;
            objs[3] = type;
            objs[4] = DataId;
            objs[5] = version;
            DataRowCollection drc = DBManager.Select(string.Format("select * from fromclient where Id={0} and DataId={1}", this.id, DataId));
            int count1 = drc.Count;
            drc = DBManager.Select(string.Format("select * from fromapple where Id={0} and DataId={1}", this.id, DataId));
            int count2 = drc.Count;
            if(count1==0&&count2==0)
            {
                DBManager.Insert(string.Format("insert into fromclient (Id,DataFromClient,DataId,ReqId) values ({0},'{1}',{2},{3})", this.id, AppleData, DataId, ReqId));  
            }
            LogInController.instance.UsersToValidateData.Enqueue(objs);
        }
        void   Exc_Config(int DataId,int ReqId)
        {
            DataRowCollection drc = DBManager.Select(string.Format("select * from fromapple where id={0}&&DataId={1}", this.id, DataId));
            object[] objs = drc[0].ItemArray;
            string   DataFromApple=(string)objs[1];
            JsonData boss = JsonMapper.ToObject(DataFromApple);
            int status=(int)boss["status"];
            if(status!=0)
            {
                DBManager.Delete(string.Format("delete from fromapple where Id={0}&&DataId={1}", this.id, DataId));
                 return;
            }
            JsonData receipt = boss["receipt"];
            JsonData info = receipt["in_app"][0];
            string ProId = (string)info["product_id"];
            SQLEnum ReqType = (SQLEnum)ReqId;
            DateTime now = DateTime.Now;
            string CurrentTime = string.Format("{0}-{1:00}-{2:00} {3:00}:{4:00}:{5:00}", now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
            if(ReqType==SQLEnum.购买了一个商品)
            {
                drc = DBManager.Select(string.Format("select Cost from Product where ProductId='{0}'", ProId));
                float cost = float.Parse(((string)drc[0][0]).Split('/')[0]);
                DBManager.Insert(string.Format("insert into buyview (ProId,day,Money,Id) values ('{0}','{1}','{2}',{3})", ProId, CurrentTime, cost, this.id));
            }
            else if (ReqType == SQLEnum.首次充值购买按钮点击)
            {
                drc = DBManager.Select(string.Format("select Cost from activity2 where ProId='{0}' ", ProId));
                float cost = float.Parse(((string)drc[0][0]).Split('/')[0]);
                DBManager.Insert(string.Format("insert into buyview (ProId,day,Money,Id) values ('{0}','{1}','{2}',{3})", ProId, CurrentTime, cost, this.id));
            }
            DBManager.Delete(string.Format("delete from fromapple where DataId={0}&&Id={1}", DataId, this.id));
        }
        void   Exc_SEG(int currentlevel) //统计数据（进入游戏的时候）
        {
            if(currentlevel>1000)
            {
                currentlevel -= 1000;
            }
            DataRowCollection drc = DBManager.Select("select LevelAgainStarsInfo,LevelEnterInfo from info");
            object[] infos = drc[0].ItemArray;
            JsonData LevelStarInfo=JsonMapper.ToObject((string)infos[0]);
            JsonData LevelEnterInfo = JsonMapper.ToObject((string)infos[1]);
            int n =(int)LevelEnterInfo[currentlevel - 1];
            n += 1;
            LevelEnterInfo[currentlevel - 1] = n;
            drc = DBManager.Select(string.Format("select CurrentLevel,Stars from player where id={0}", this.id));
            object[] properties = drc[0].ItemArray;
            int db_currentlevel = (int)properties[0];
            int star= (int)JsonMapper.ToObject((string)properties[1])[currentlevel-1];
            JsonData curdata = LevelStarInfo[currentlevel - 1];
            if(currentlevel<db_currentlevel)
            {
                int changedstar = 0;
                switch (star)
                {
                    case 0:
                        changedstar = (int)curdata["ZeroStar"];
                        changedstar += 1;
                        curdata["ZeroStar"] = changedstar;
                        break;
                    case 1:
                        changedstar = (int)curdata["OneStar"];
                        changedstar += 1;
                        curdata["OneStar"] = changedstar;
                        break;
                    case 2:
                        changedstar = (int)curdata["TwoStar"];
                        changedstar += 1;
                        curdata["TwoStar"] = changedstar;
                        break;
                    case 3:
                        changedstar = (int)curdata["ThreeStar"];
                        changedstar += 1;
                        curdata["ThreeStar"] = changedstar;
                        break;
                }
            }
            DBManager.Update(string.Format("update info set LevelAgainStarsInfo='{0}',LevelEnterInfo='{1}'", LevelStarInfo.ToJson(), LevelEnterInfo.ToJson()));
        }
        string GetGameCenterName(string name,int type) 
        {
            
            DataRowCollection drc = DBManager.Select(string.Format("select Fbid,Name from player where id={0}", this.id));
            string _Fbid=(string)drc[0][0];
            string _Name = (string)drc[0][1];
            if (_Fbid == "None")
            {
                if (name != "(null)")
                {
                    /*****************************************/
                    name = Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
                    /*****************************************/
                    _Name = name;
                    DBManager.Update(string.Format("update player set Name='{0}' where id={1}", name, this.id));
                }
            }
            JsonData jd = new JsonData();
            try
            {
                _Name = Encoding.UTF8.GetString(Convert.FromBase64String(_Name));
            }
            catch
            {
            
            
            }
            jd["Name"] = _Name;
            return GetJsonString(type,jd);
        }
        string Redirector()//重定向器 
        {
            JsonData jd = new JsonData();
            string ip = "54.238.250.86";
            int port = 9999;
            jd["ip"] = ip;
            jd["port"] = port;
            return GetJsonString(100, jd);
        }
        string ReducePower(int type)
        {
            JsonData jd = new JsonData();
            jd["mm"] = 1;
            return GetJsonString(type, jd);
        }
        string RefreshItemCount(int type)
        {
            JsonData jd = new JsonData();
            jd["mm"] = 1;
            return GetJsonString(type, jd);
        }
        string GameFailToContinueUI(int type)
        {
            JsonData jd = new JsonData();
            jd["mm"] = 1;
            return GetJsonString(type, jd);

        }
        string FuckingFunc(int type)
        {
            JsonData jd = new JsonData();
            jd["fuck"] = 1;
            return GetJsonString(type, jd);
        }
        string ActivityRewardRankUI(int type)//打开活动奖励界面,排名-头像-名字-物品编号-数量
        {
            DataRowCollection drc = DBManager.Select("select Id,FbHead,Name,TargetCollectedNumber from player order by TargetCollectedNumber DESC ");
            DataRowCollection drc1 = DBManager.Select("select targettype from activity1 where id=(select id from currentactivity where type=1)");
            string myself = "";
            List<string> others = new List<string>();
            for (int i = 0; i < drc.Count; i++)
            {
                string _Name =Encoding.UTF8.GetString(Convert.FromBase64String((string)drc[i][2]));
                if ((int)drc[i][0] == id)
                {
                    myself = string.Format("{0},{1},{2},{3},{4}", i + 1, (string)drc[i][1], _Name, a_GetTypeCode((string)drc1[0][0]), (int)drc[i][3]);
                }
                if (i < 5)
                {
                    string fy = string.Format("{0},{1},{2},{3},{4}", i + 1, (string)drc[i][1], _Name, a_GetTypeCode((string)drc1[0][0]), (int)drc[i][3]);
                    others.Add(fy);
                }
            }
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            jd.Add(myself);
            for (int i = 0; i < others.Count; i++)
            {
                jd.Add(others[i]);
            }
            return GetJsonString(type, jd);
        }
        string EnterChooseLevelScene(int type)
        {
            DataRowCollection drc = DBManager.Select("select * from currentactivity where Type=1 ");
            JsonData boss = new JsonData();
            boss.SetJsonType(JsonType.Array);
            if (drc.Count != 0)
            {
                int ac_id = (int)drc[0][0];
                DataRowCollection drc1 = DBManager.Select(string.Format("select * from activity1 where Id={0} ", ac_id));
                object[] objs = drc1[0].ItemArray;
                int TargetCollectedNum = (int)objs[4];
                int[] array = new int[6];
                for (int i = 0; i < array.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        int code = a_GetTypeCode((string)objs[i + 5]);
                        array[i] = code;
                    }
                    else array[i] = (int)objs[i +5];
                }
                drc = DBManager.Select(string.Format("select TargetCollectedNumber,ActivityRewardState,CurrentLevel from player where id={0} ", id));
                int collectednum = (int)drc[0][0];
                int rewardstate = (int)drc[0][1];
                int CurrentLevel = (int)drc[0][2];
                if (rewardstate == 1)
                {
                    return GetJsonString(type, boss);
                }
                else
                {
                    if (collectednum < TargetCollectedNum)
                    {
                        return GetJsonString(type, boss);
                    }
                    else
                    {
                        /***********统计活动完成**************/
                        DataRowCollection drc11 = DBManager.Select("select CollectActivityInfo from info");
                        JsonData CollectActivityDataStastic = JsonMapper.ToObject((string)drc[0][0]);
                        int a_count=(int)CollectActivityDataStastic[CurrentLevel-1];
                        a_count += 1;
                        CollectActivityDataStastic[CurrentLevel - 1] = a_count;
                        DBManager.Update(string.Format("update info set CollectActivityInfo='{0}'", CollectActivityDataStastic.ToJson()));
                        /*************************/
                        JsonData data = new JsonData();
                        data.SetJsonType(JsonType.Array);
                        string CmdText = "update player set ";
                        JsonData jd = null;
                        int OrigItemCount = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            if (i % 2 == 0)
                            {
                                jd = new JsonData();
                                jd["Id"] = array[i];
                                string Name = GetStringName3(array[i]);
                                CmdText += Name + "=";
                                DataRowCollection drc12 = DBManager.Select(string.Format("select {0} from player where Id={1}", Name, this.id));
                                OrigItemCount=(int)drc12[0][0];
                            }
                            else
                            {
                                jd["Count"] = array[i];
                                int NewItemCount=OrigItemCount+array[i];
                                CmdText += NewItemCount;
                                if (i != array.Length - 1)
                                {
                                    CmdText += ",";
                                }
                                data.Add(jd);
                            }
                        }
                        boss.Add(data);
                        CmdText += ",ActivityRewardState=1" + " where id=" + id;
                        DBManager.Update(CmdText);
                        drc = DBManager.Select(string.Format("select Gold,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where id={0}", id));
                        objs = drc[0].ItemArray;
                        JsonData Properties = new JsonData();
                        Properties.SetJsonType(JsonType.Array);
                        for (int i = 0; i < objs.Length; i++)
                        {
                            Properties.Add(objs[i]);
                        }
                        boss.Add(Properties);
                    }

                }
            }

            return GetJsonString(type, boss);
        }
        string GetNameItem(int ItemId) 
        {
         //1为十字清除，2为交换道具，3为铲子道具，4蘑菇道具，5为染色道具，6为全屏道具
            string ItemName = null;
            switch (ItemId)
            {
                case 0:
                    ItemName = "MagicItem";
                    break;
                case 2:
                    ItemName = "ColorItem";
                    break;
                case 3:
                    ItemName = "LineItem";
                    break;
                case 4:
                    ItemName = "ExchangeItem";
                    break;
                case 5:
                    ItemName = "HammerItem";
                    break;
                case 6:
                    ItemName = "CrossItem";
                    break;
            }
            return ItemName;
        }
        string GetStringName3(int RewardType) //名字转换函数1
        {
            /****
          "icon_item_coin",         //0
          "icon_item_crossClear",   //1
          "icon_item_dye",          //2
          "icon_item_line",         //3
          "icon_item_magical",      //4
          "icon_item_move",         //5
          "icon_item_oneClear",     //6
          ***/
            string ItemName = null;
            switch (RewardType)
            {
                case 4:
                    ItemName = "MagicItem";
                    break;
                case 0:
                    ItemName = "Gold";
                    break;
                case 2:
                    ItemName = "ColorItem";
                    break;
                case 3:
                    ItemName = "LineItem";
                    break;
                case 5:
                    ItemName = "ExchangeItem";
                    break;
                case 6:
                    ItemName = "HammerItem";
                    break;
                case 1:
                    ItemName = "CrossItem";
                    break;
            }

            return ItemName;
        }
        string GetCurrentActivity(int type)//获取当前活动
        {
            /**搜集活动 
     搜集物品的编号 
    "icon_apple",             //0
    "icon_blueBerry",         //1
    "icon_carrot",            //2
    "icon_coloredFlower",     //3
    "icon_coloredIce",        //4
    "icon_dye",               //5
    "icon_egg",               //6
    "icon_eggplant",          //7
    "icon_exloped",           //8
    "icon_giftBox",           //9
    "icon_ice",               //10
    "icon_ironDrum",          //11
    "icon_line",              //12
    "icon_magical",           //13
    "icon_nut",               //14
    "icon_pear",              //15
    "icon_stump",             //16
    "icon_tomato",            //17
    "icon_waterBucket",       //18

    获取奖励的编号
    "icon_item_coin",         //0
    "icon_item_crossClear",   //1
    "icon_item_dye",          //2
    "icon_item_line",         //3
    "icon_item_magical",      //4
    "icon_item_move",         //5
    "icon_item_oneClear",     //6
         ***/
            JsonData activity1 = new JsonData();
            activity1.SetJsonType(JsonType.Array);
            JsonData activity2 = new JsonData();
            activity2.SetJsonType(JsonType.Array);
            DataRowCollection drc = DBManager.Select("select * from currentactivity ");
            if (drc.Count != 0)//当前有活动
            {
                for (int k = 0; k < drc.Count; k++)
                {
                    object[] activity = drc[k].ItemArray;
                    int ac_id = (int)activity[0];
                    int ac_type = (int)activity[1];
                    if (ac_type == 1)//活动1
                    {
                        DataRowCollection drc1 = DBManager.Select(string.Format("select * from activity1 where Id={0} ", ac_id));
                        activity = drc1[0].ItemArray;
                        DateTime EndTime = (DateTime)activity[12];
                        if(EndTime>DateTime.Now)
                        {

                            drc1 = DBManager.Select(string.Format("select TargetCollectedNumber,ActivityRewardState from player where Id={0} ", id));
                            int TargetCollectedNumber = (int)drc1[0][0];
                            int ActivityRewardState = (int)drc1[0][1];
                            List<object> objs = new List<object>();
                            for (int i = 0; i < activity.Length; i++)
                            {
                                if (i == 3 || i == 5 || i == 7 || i == 9)
                                {
                                    activity[i] = a_GetTypeCode((string)activity[i]);
                                }
                                objs.Add(activity[i]);
                                if (i == 4)
                                {
                                    objs.Add(TargetCollectedNumber);
                                }
                            }
                            for (int i = 0; i < objs.Count; i++)
                            {
                                try
                                {
                                    activity1.Add(objs[i]);
                                }
                                catch
                                {
                                    activity1.Add(objs[i].ToString());
                                }
                            }
                            activity1.Add(TargetCollectedNumber);
                        
                        }

                    }
                    else if (ac_type == 2)//活动2
                    {
                        bool Flag = false;
                        DataRowCollection drc5 = DBManager.Select(string.Format("select ProId from activity2 where Id={0} ", ac_id));
                        string ProId=(string)drc5[0][0];
                        if (ProId == "com.crushyvegie.greatdealpackage")
                        {
                            DataRowCollection drc2 = DBManager.Select(string.Format("select FristBuyState from player where Id={0} ", id));
                            int FristBuyState = (int)drc2[0][0];
                            if (FristBuyState == 1)
                            {
                                Flag = true;
                            }
                        }
                        if (!Flag)
                        {
                            DataRowCollection drc3 = DBManager.Select(string.Format("select * from activity2 where Id={0} ", ac_id));
                            activity = drc3[0].ItemArray;
                            DateTime EndTime = (DateTime)activity[17];
                            if(EndTime>DateTime.Now)
                            {
                                for (int i = 0; i < activity.Length; i++)
                                {
                                    try
                                    {
                                        if (i == 3 || i == 5 || i == 7 || i == 9 || i == 11 || i == 13)
                                        {
                                            activity[i] = a_GetTypeCode((string)activity[i]);
                                        }
                                        activity2.Add(activity[i]);
                                    }
                                    catch
                                    {
                                        activity2.Add(activity[i].ToString());
                                    }
                                }
                            }
                        }
                    }

                }
            }
            JsonData boss = new JsonData();
            boss["Activity1"] = activity1;
            boss["Activity2"] = activity2;
            return GetJsonString(type, boss);
        }
        string OpenPowerUI(int type)
        {
            JsonData jd = new JsonData();
            jd["fuck"] = 0;
            return GetJsonString(type, jd);
        }
        string BuyPowerUI(int type)
        {
            JsonData jd = new JsonData();
            jd["fuck"] = 0;
            return GetJsonString(type, jd);
        }
        string NewFriendMsg(int type) //有无消息
        {
            DataRowCollection drc = DBManager.Select(string.Format("select Friends from player where Id={0}", id));
            string f = (string)drc[0][0];
            JsonData Friends = JsonMapper.ToObject(f);
            int state =0;
            for (int i = 0; i < Friends.Count; i++)
            {
                int _CheckState = (int)Friends[i]["CheckState"];
                Friends[i]["CheckState"] = 1;
                if (_CheckState == 0)
                {
                    state = 1;
                }
            }
            DBManager.Update(string.Format("update player set Friends='{0}' where Id={1}", Friends.ToJson(), id));
            JsonData jd = new JsonData();
            jd["state"] = state;
            return GetJsonString(type, jd);
        }
        string ReadyToEnterGame(int CurrentLevel, int type)//准备进入游戏
        {
            if (CurrentLevel>1000)
            {
                CurrentLevel -= 1000;
            }
            JsonData js_data = new JsonData();
            js_data.SetJsonType(JsonType.Array);
            DataRowCollection drc = DBManager.Select(string.Format("select Friends,Fbid,FbHead,FbName from player where Id={0}", id));
            string f = (string)drc[0][0];
            string MyFbid = (string)drc[0][1];
            if(MyFbid=="None")
            {
                return GetJsonString(type, js_data);
            }
            JsonData Friends = JsonMapper.ToObject(f);
            /****************************************************/
            for (int i = 0; i < Friends.Count; i++)
            {
                try
                {
                    string NameOfNormal1 = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                    Friends[i]["FbName"] = NameOfNormal1;
                }
                catch 
                {
                
                
                }
            }
            /****************************************************/

            /*****************************************/
            string Self_Name = (string)drc[0][3];
            try 
            {
                Self_Name = Encoding.UTF8.GetString(Convert.FromBase64String(Self_Name));
            }
            catch
            {

            }
            
            /*****************************************/
            JsonData dd = JsonMapper.ToObject("{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", (string)drc[0][1], Self_Name, (string)drc[0][2], 0, 1) + "}");
            Friend ff = new Friend(dd);
            Friends.Add(ff.ToJsonData());
            List<Friend> lst = new List<Friend>();
            for (int i = 0; i < Friends.Count; i++)
            {
                drc = DBManager.Select(string.Format("select Scores from player where Fbid='{0}'", (string)Friends[i]["Fbid"]));
                string s = (string)drc[0][0];
                JsonData data = JsonMapper.ToObject(s);
                int score = (int)data[CurrentLevel - 1];
                Friend cf = new Friend(Friends[i]);
                cf.Score = score;
                lst.Add(cf);
            }
            for (int i = 0; i < lst.Count - 1; i++)
            {

                int Max = lst[i].Score;
                for (int j = i + 1; j < lst.Count; j++)
                {
                    if (Max < lst[j].Score)
                    {
                        Friend temp = lst[i];
                        lst[i] = lst[j];
                        lst[j] = temp;
                        Max = lst[i].Score;
                    }
                }
            }
            JsonData TopThreePlayers = new JsonData();
            TopThreePlayers.SetJsonType(JsonType.Array);
            for (int i = 0; i < lst.Count; i++)
            {
                Friend f1 = lst[i];
                JsonData m = f1.ToJsonData();
                m["Score"] = f1.Score;
                TopThreePlayers.Add(m);
                if (i == 2)
                {
                    break;
                }
            }
            for (int i = 0; i < TopThreePlayers.Count; i++)
            {
                JsonData dt = new JsonData();
                dt["FbHead"] = (string)TopThreePlayers[i]["FbHead"];
                dt["FbName"] = (string)TopThreePlayers[i]["FbName"];
                dt["Score"] = (int)TopThreePlayers[i]["Score"];
                js_data.Add(dt);
            }
            return GetJsonString(type, js_data);
        }
        string GameFailGetRank(int CurrentLevel, int type) //获取游戏失败后的排行榜
        {
            if(CurrentLevel>1000)
            {
                CurrentLevel -= 1000;
            }
            JsonData js_data = new JsonData();
            js_data.SetJsonType(JsonType.Array);
            DataRowCollection drc = DBManager.Select(string.Format("select Friends,Fbid,FbHead,FbName from player where Id={0}", id));
            string f = (string)drc[0][0];
            string SelfFbid = (string)drc[0][1];
            if (SelfFbid == "None")
            {
                return GetJsonString(type, js_data);
            }
            JsonData Friends = JsonMapper.ToObject(f);
            /****************************************************/
            for (int i = 0; i < Friends.Count;i++)
            {
                try
                {
                    string NameOfNormal1 = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                    Friends[i]["FbName"] = NameOfNormal1;
                }
                catch 
                {
                
                }
                
            }
            /****************************************************/


            /*****************************************/
            string Self_Name = (string)drc[0][3];
            try
            {
                Self_Name = Encoding.UTF8.GetString(Convert.FromBase64String(Self_Name));
            }
            catch
            {
            
            }
           
            /*****************************************/
            JsonData dd = JsonMapper.ToObject("{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", (string)drc[0][1], Self_Name, (string)drc[0][2], 0, 1) + "}");
            Friend ff = new Friend(dd);
            Friends.Add(ff.ToJsonData());
            List<Friend> lst = new List<Friend>();
            for (int i = 0; i < Friends.Count; i++)
            {
                drc = DBManager.Select(string.Format("select Scores from player where Fbid='{0}'", (string)Friends[i]["Fbid"]));
                string s = (string)drc[0][0];
                JsonData data = JsonMapper.ToObject(s);
                int score = (int)data[CurrentLevel - 1];
                Friend cf = new Friend(Friends[i]);
                cf.Score = score;
                lst.Add(cf);
            }
            for (int i = 0; i < lst.Count - 1; i++)
            {

                int Max = lst[i].Score;
                for (int j = i + 1; j < lst.Count; j++)
                {
                    if (Max < lst[j].Score)
                    {
                        Friend temp = lst[i];
                        lst[i] = lst[j];
                        lst[j] = temp;
                        Max = lst[i].Score;
                    }
                }
            }
            JsonData TopThreePlayers = new JsonData();
            TopThreePlayers.SetJsonType(JsonType.Array);
            for (int i = 0; i < lst.Count; i++)
            {
                Friend f1 = lst[i];
                JsonData m = f1.ToJsonData();
                m["Score"] = f1.Score;
                TopThreePlayers.Add(m);
                if (i == 2)
                {
                    break;
                }
            }
            for (int i = 0; i < TopThreePlayers.Count; i++)
            {
                JsonData dt = new JsonData();
                dt["FbHead"] = (string)TopThreePlayers[i]["FbHead"];
                dt["FbName"] = (string)TopThreePlayers[i]["FbName"];
                dt["Score"] = (int)TopThreePlayers[i]["Score"];
                js_data.Add(dt);
            }
            return GetJsonString(type, js_data);
        }
        string GameSuccessGetRank(int CurrentLevel, int type)//获取游戏成功后的排行榜
        {
            if (CurrentLevel > 1000)
            {
                CurrentLevel -= 1000;
            }
            JsonData js_data = new JsonData();
            js_data.SetJsonType(JsonType.Array);
            DataRowCollection drc = DBManager.Select(string.Format("select Friends,Fbid,FbHead,FbName from player where Id={0}", id));
            string f = (string)drc[0][0];
            string SelfFbid=(string)drc[0][1];
            if(SelfFbid=="None")
            {
                return GetJsonString(type, js_data);
            }
            JsonData Friends = JsonMapper.ToObject(f);
            /****************************************************/
            for (int i = 0; i < Friends.Count; i++)
            {
                try 
                {
                    string NameOfNormal1 = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                    Friends[i]["FbName"] = NameOfNormal1;
                }
                catch 
                {
                
                }
               
            }

            /*****************************************/
            string Self_Name = (string)drc[0][3];
            try
            {
                Self_Name = Encoding.UTF8.GetString(Convert.FromBase64String(Self_Name));
            }
            catch
            {

            }
            /*****************************************/

            JsonData dd = JsonMapper.ToObject("{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", (string)drc[0][1], Self_Name, (string)drc[0][2], 0, 1) + "}");
            Friend ff = new Friend(dd);
            Friends.Add(ff.ToJsonData());
            List<Friend> lst = new List<Friend>();
            for (int i = 0; i < Friends.Count; i++)
            {
                drc = DBManager.Select(string.Format("select Scores from player where Fbid='{0}'", (string)Friends[i]["Fbid"]));
                string s = (string)drc[0][0];
                JsonData data = JsonMapper.ToObject(s);
                int score = (int)data[CurrentLevel - 1];
                Friend cf = new Friend(Friends[i]);
                cf.Score = score;
                lst.Add(cf);
            }
            for (int i = 0; i < lst.Count - 1; i++)
            {

                int Max = lst[i].Score;
                for (int j = i + 1; j < lst.Count; j++)
                {
                    if (Max < lst[j].Score)
                    {
                        Friend temp = lst[i];
                        lst[i] = lst[j];
                        lst[j] = temp;
                        Max = lst[i].Score;
                    }
                }
            }
            JsonData TopThreePlayers = new JsonData();
            TopThreePlayers.SetJsonType(JsonType.Array);
            for (int i = 0; i < lst.Count; i++)
            {
                Friend f1 = lst[i];
                JsonData m = f1.ToJsonData();
                m["Score"] = f1.Score;
                TopThreePlayers.Add(m);
                if (i == 2)
                {
                    break;
                }
            }
            for (int i = 0; i < TopThreePlayers.Count; i++)
            {
                JsonData dt = new JsonData();
                dt["FbHead"] = (string)TopThreePlayers[i]["FbHead"];
                dt["FbName"] = (string)TopThreePlayers[i]["FbName"];
                dt["Score"] = (int)TopThreePlayers[i]["Score"];
                js_data.Add(dt);
            }
            return GetJsonString(type, js_data);
        }
        string OpenSettingsInGame(int type)
        {
            JsonData jd = new JsonData();
            jd["fuck"] = 1;
            return GetJsonString(type, jd);
        }
        string ExitGameConfirmUI(int type)
        {
            JsonData jd = new JsonData();
            jd["mn"] = 1;
            return GetJsonString(type, jd);
        }
        string UseItem(int ItemId, int type) // 1为十字清除，2为交换道具，3为铲子道具，4蘑菇道具，5为染色道具，6为全屏道具
        {
            string name = GetNameItem(ItemId);
            DataRowCollection drc = DBManager.Select(string.Format("select {0} from player where Id={1}", name, id));
            int count = (int)drc[0][0];
            if (count > 0)
            {
                count -= 1;
            }
            else count = 0;
            DBManager.Update(string.Format("update  player set {0}={1} where Id={2}", name, count, id));
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            jd.Add(ItemId);
            jd.Add(count);
            /**************统计使用道具***************/
            drc = DBManager.Select("select UseItemInfo from info");
            JsonData ItemInfos = JsonMapper.ToObject((string)drc[0][0]);
            int _count = (int)ItemInfos[name];
            _count += 1;
            ItemInfos[name] = _count;
            DBManager.Update(string.Format("update info set UseItemInfo='{0}'", ItemInfos.ToJson()));
            /*****************************/
            return GetJsonString(type, jd);
        }
        string UseGold(JsonData dt, int type)
        {
            int count = (int)dt["Delta"];
            int CurrentLevel=(int)dt["CurrentLevel"];
            if(CurrentLevel>1000)
            {
                CurrentLevel -= 1000;
            }
            int flag = 0;
            DataRowCollection drc = DBManager.Select(string.Format("select Gold from player where Id={0}", id));
            int gold = (int)drc[0][0];
            if (gold >=count)
            {
                gold -= count;
                flag = 1;
                DBManager.Update(string.Format("update player set Gold={0} where id={1}", gold, id));
            }
            JsonData jd = new JsonData();
            jd["Gold"] = gold;
            jd["flag"] = flag;
            /**************每一关玩家成功购买步数或者时间的成功次数******************/
            drc = DBManager.Select("select LevelBuyStepOrTimeInfo from info");
            JsonData info = JsonMapper.ToObject((string)drc[0][0]);
            int BuyCount=(int)info[CurrentLevel-1];
            BuyCount += 1;
            info[CurrentLevel - 1]=BuyCount;
            DBManager.Update(string.Format("update info set LevelBuyStepOrTimeInfo='{0}'", info.ToJson()));
            /***********************************************************************/
            return GetJsonString(type, jd);
        }
        string InitializeScores() //初始化scores
        {
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            for (int i = 0; i < 200; i++)
            {
                jd.Add(0);
            }
            return jd.ToJson();

        }
        string OpenChooseMapUI(int type)
        {
            JsonData data = new JsonData();
            data.SetJsonType(JsonType.Array);
            return GetJsonString(type, data);
        }
        string EnterChooseBigLevelUI(int type) //选关界面
        {
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            return GetJsonString(type, jd);
        }
        string LogIn(JsonData data, int type)//普通登录 
        {
            data[13] = Convert.ToBase64String(Encoding.UTF8.GetBytes((string)data[13]));
            JsonData js = new JsonData();
            js.SetJsonType(JsonType.Array);
            int id = (int)data[0];
            string Pid = (string)data[1];
            this.Pid = Pid;
            string Fbid = (string)data[2];
            int gold = (int)data[3];
            int level = (int)data[4];
            JsonData Boss = data[5];
            string stars = Boss["Stars"].ToJson();
            int line = (int)data[6];
            int magic = (int)data[7];
            int color = (int)data[8];
            int exchange = (int)data[9];
            int hammer = (int)data[10];
            int cross = (int)data[11];
            int power = (int)data[12];
            string name = (string)data[13];
            int priority = 0;
            DataRowCollection drc11 = DBManager.Select(string.Format("select * from player where Id={0}", id));
            if (drc11.Count==0)
            {
                priority = 1;
            }
            if (priority == 0)//通过Id查询
            {
                this.id = id;
                DataRowCollection drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where id={0}", id));
                object[] columns = drc[0].ItemArray;
                //UpdatePlayerWithClientOrServer(data, columns);
                drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where id={0}", id));
                columns = drc[0].ItemArray;
                for (int j = 0; j < columns.Length; j++)
                {
                    if (j == 14)
                    {
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch
                        {

                        }
                    }
                    if (j == 0)
                    {
                        this.id = (int)columns[0];
                        
                    }
                    if (j == 6)
                    {
                        JsonData jd = JsonMapper.ToObject(stars);
                        JsonData boss = new JsonData();
                        boss["Stars"] = jd;
                        js.Add(Boss);
                    }
                    else js.Add(columns[j]);
                }

            }
            if (priority == 1)//通过Pid查询
            {
                DataRowCollection drc1 = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where Pid='{0}'", Pid));
                if (drc1.Count != 0)
                {
                    DataRow row = drc1[0];
                    object[] columns = row.ItemArray;
                    this.id = (int)columns[0];
                    for (int j = 0; j < columns.Length; j++)
                    {
                        if (j == 14)
                        {
                            try
                            {
                                columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                            }
                            catch
                            {

                            }
                        }
                        if (j == 6)
                        {
                            JsonData jd = JsonMapper.ToObject(stars);
                            JsonData boss = new JsonData();
                            boss["Stars"] = jd;
                            js.Add(Boss);
                        }
                        else js.Add(columns[j]);
                    }
                }
                else priority = 2;
            }
            if (priority == 2)//先创建一个玩家记录再通过Pid查询
            {
                DBManager.Insert(string.Format("insert into player (Pid,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,Scores,Friends)  values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}') ", Pid, gold, level, stars, line, magic, color, exchange, hammer, cross, power, name, InitializeScores(), "[]"));
                DataRowCollection drc2 = DBManager.Select(string.Format("select Id from player where Pid='{0}'", Pid));
                this.id = (int)drc2[0][0];
                name = "Guest" + this.id;
                /*****************************************/
                name=Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
                /*****************************************/
                DBManager.Update(string.Format("update player set Name='{0}' where id={1}", name, this.id));
                drc2 = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where Id='{0}'", this.id));
                DataRow row = drc2[0];
                object[] columns = row.ItemArray;
                for (int j = 0; j < columns.Length; j++)
                {
                    if(j==14)
                    {
                        /*****************************************/
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch
                        {

                        }
                       
                        /*****************************************/
                    }
                    if (j == 6)
                    {
                        JsonData jd = JsonMapper.ToObject(stars);
                        JsonData boss = new JsonData();
                        boss["Stars"] = jd;
                        js.Add(Boss);
                    }
                    else js.Add(columns[j]);
                }
            }
            return GetJsonString(type, js);
        }
        string LogInDuringTheGame(JsonData data, JsonData Req, int type)
        {
            data[13] = Convert.ToBase64String(Encoding.UTF8.GetBytes((string)data[13]));
            JsonData js = new JsonData();
            js.SetJsonType(JsonType.Array);
            int id = (int)data[0];
            string Pid = (string)data[1];
            this.Pid = Pid;
            string Fbid = (string)data[2];
            int gold = (int)data[3];
            int level = (int)data[4];
            JsonData Boss = data[5];
            string stars = Boss["Stars"].ToJson();
            int line = (int)data[6];
            int magic = (int)data[7];
            int color = (int)data[8];
            int exchange = (int)data[9];
            int hammer = (int)data[10];
            int cross = (int)data[11];
            int power = (int)data[12];
            string name = (string)data[13];
            int priority = 0;
            DataRowCollection drc11 = DBManager.Select(string.Format("select * from player where Id={0}", id));
            if (drc11.Count == 0)
            {
                priority = 1;
            }
            if (priority == 0)//通过Id查询
            {
                this.id = id;
                DataRowCollection drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where id={0}", id));
                object[] columns = drc[0].ItemArray;
                //UpdatePlayerWithClientOrServer(data, columns);
                drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where id={0}", id));
                columns = drc[0].ItemArray;
                for (int j = 0; j < columns.Length; j++)
                {
                    if (j == 14)
                    {
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch
                        {

                        }
                    }
                    if (j == 0)
                    {
                        this.id = (int)columns[0];

                    }
                    if (j == 6)
                    {
                        JsonData jd = JsonMapper.ToObject(stars);
                        JsonData boss = new JsonData();
                        boss["Stars"] = jd;
                        js.Add(Boss);
                    }
                    else js.Add(columns[j]);
                }

            }
            if (priority == 1)//通过Pid查询
            {
                DataRowCollection drc1 = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where Pid='{0}'", Pid));
                if (drc1.Count != 0)
                {
                    DataRow row = drc1[0];
                    object[] columns = row.ItemArray;
                    this.id = (int)columns[0];
                    for (int j = 0; j < columns.Length; j++)
                    {
                        if (j == 14)
                        {
                            try
                            {
                                columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                            }
                            catch
                            {

                            }
                        }
                        if (j == 6)
                        {
                            JsonData jd = JsonMapper.ToObject(stars);
                            JsonData boss = new JsonData();
                            boss["Stars"] = jd;
                            js.Add(Boss);
                        }
                        else js.Add(columns[j]);
                    }
                }
                else priority = 2;
            }
            if (priority == 2)//先创建一个玩家记录再通过Pid查询
            {
                DBManager.Insert(string.Format("insert into player (Pid,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,Scores,Friends)  values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}') ", Pid, gold, level, stars, line, magic, color, exchange, hammer, cross, power, name, InitializeScores(), "[]"));
                DataRowCollection drc2 = DBManager.Select(string.Format("select Id from player where Pid='{0}'", Pid));
                this.id = (int)drc2[0][0];
                name = "Guest" + this.id;
                /*****************************************/
                name = Convert.ToBase64String(Encoding.UTF8.GetBytes(name));
                /*****************************************/
                DBManager.Update(string.Format("update player set Name='{0}' where id={1}", name, this.id));
                drc2 = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where Id='{0}'", this.id));
                DataRow row = drc2[0];
                object[] columns = row.ItemArray;
                for (int j = 0; j < columns.Length; j++)
                {
                    if (j == 14)
                    {
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch
                        {

                        }
                    }
                    if (j == 6)
                    {
                        JsonData jd = JsonMapper.ToObject(stars);
                        JsonData boss = new JsonData();
                        boss["Stars"] = jd;
                        js.Add(Boss);
                    }
                    else js.Add(columns[j]);
                }
            }
            string sss = GetJsonString(type, js);
            JsonData ddd = JsonMapper.ToObject(sss);
            ddd["CurrentReq"] = Req;
            return ddd.ToJson();
        }
        string OpenMsgUI(int type)//消息界面信息
        {
            JsonData FirendsWithMsg = new JsonData();
            FirendsWithMsg.SetJsonType(JsonType.Array);
            DataRowCollection drc = DBManager.Select(string.Format("select Friends from player where Id={0}", id));
            string f = (string)drc[0][0];
            JsonData Friends = JsonMapper.ToObject(f);
            for (int i = 0; i < Friends.Count; i++)
            {
                int _MsgCount = (int)Friends[i]["MsgCount"];
                Friends[i]["CheckState"] = 1;
                if (_MsgCount != 0)
                {
                    try
                    {
                        Friends[i]["FbName"] = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                    }
                    catch
                    {

                    }
                   
                    FirendsWithMsg.Add(Friends[i]);
                }
            }
            return GetJsonString(type, FirendsWithMsg);
        }
        string DonatePowerToFriends(int type)
        {
            DataRowCollection drc = DBManager.Select(string.Format("select Friends,Power,Fbid from player where Id={0}", id));
            string f = (string)drc[0][0];
            int power = (int)drc[0][1];
            string Fbid = (string)drc[0][2];
            JsonData MyFriends = JsonMapper.ToObject(f);
            for (int i = 0; i < MyFriends.Count; i++)
            {
                string _Fbid = (string)MyFriends[i]["Fbid"];
                drc = DBManager.Select(string.Format("select Friends from player where Fbid='{0}'", _Fbid));
                string f1 = (string)drc[0][0];
                JsonData FriendsOfMyFriend = JsonMapper.ToObject(f1);
                for (int j = 0; j < FriendsOfMyFriend.Count; j++)
                {
                    if ((string)FriendsOfMyFriend[j]["Fbid"] == Fbid)
                    {
                        int _MsgCount = (int)FriendsOfMyFriend[j]["MsgCount"];
                        _MsgCount += 1;
                        FriendsOfMyFriend[j]["MsgCount"] = _MsgCount;
                        FriendsOfMyFriend[j]["CheckState"] = 0;
                        DBManager.Update(string.Format("update player set Friends='{0}' where Fbid='{1}'", FriendsOfMyFriend.ToJson(), _Fbid));
                        break;
                    }
                }
            }
            if (MyFriends.Count != 0)
            {
                power -= 1;
            }
            DBManager.Update(string.Format("update player set PresentPowerState=1,Power={0} where Id={1}", power, id));
            JsonData jd = new JsonData();
            jd["Count"] = MyFriends.Count;
            return GetJsonString(type, jd);
        }
        string RecieveFriendDonatedPower(JsonData data, int type)//接受好友赠送的体力
        {
            string msg= "";
            int flag = (int)data["flag"];
            if (flag == 1)
            {
                JsonData dt = data["friend"];
                string Fbid = (string)dt["Fbid"];
                DataRowCollection drc = DBManager.Select(string.Format("select Friends,Power from player where Id={0}", id));
                string f = (string)drc[0][0];
                int power = (int)drc[0][1];
                power += 1;
                JsonData Friends = JsonMapper.ToObject(f);
                JsonData FirendsWithMsg = new JsonData();
                FirendsWithMsg.SetJsonType(JsonType.Array);
                for (int i = 0; i < Friends.Count; i++)
                {
                    int _MsgCount = (int)Friends[i]["MsgCount"];
                    if (Fbid == (string)Friends[i]["Fbid"])
                    {
                        if (_MsgCount == 0)
                        {
                            continue;
                        }
                        _MsgCount -= 1;
                        Friends[i]["MsgCount"] = _MsgCount;
                        DBManager.Update(string.Format("update player set Friends='{0}',Power={1} where Id={2}", Friends.ToJson(), power, id));
                    }
                    if (_MsgCount != 0)
                    {
                        try
                        {
                            Friends[i]["FbName"] = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                        }
                        catch 
                        { 

                        }
                        FirendsWithMsg.Add(Friends[i]);
                    }
                }
                msg = GetJsonString(type, FirendsWithMsg);
            }
            else 
            {
                DataRowCollection drc = DBManager.Select(string.Format("select Friends from player where Id={0}", id));
                string f = (string)drc[0][0];
                JsonData Friends = JsonMapper.ToObject(f);
                JsonData FirendsWithMsg = new JsonData();
                FirendsWithMsg.SetJsonType(JsonType.Array);
                for (int i = 0; i < Friends.Count; i++)
                {
                    int _MsgCount = (int)Friends[i]["MsgCount"];
                    if (_MsgCount != 0)
                    {
                        try
                        {
                            Friends[i]["FbName"] = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                        }
                        catch
                        {

                        }
                        FirendsWithMsg.Add(Friends[i]);
                    }
                }
                msg = GetJsonString(type, FirendsWithMsg);
            }
            return msg;
        }
        string GetDailyReward(int type,int IsDouble)//领取每日礼包
        {
            DataRowCollection drc = DBManager.Select(string.Format("select DailyRewardCount from player where Id={0}", id));
            int count = (int)drc[0][0];
            drc = DBManager.Select(string.Format("select RewardType,RewardNumber from dailyreward where Day={0}", count));
            int r_type = (int)drc[0][0];
            int r_number = (int)drc[0][1];
            if(IsDouble==1)
            {
                r_number*=2;
            }
            string Name = GetStringName1(r_type);
            drc = DBManager.Select(string.Format("select {0} from player where id={1}", Name, id));
            int sum = r_number + (int)drc[0][0];
            DBManager.Update(string.Format("update player set DailyRewardState=1,{0}={1} where id={2}", Name, sum, id));
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            jd.Add(r_type);
            jd.Add(sum);
            return GetJsonString(type, jd);
        }
        string GetDailyRewardUI(int type)//每日登陆奖励列表
        {
            DataRowCollection drc = DBManager.Select("select * from dailyreward");
            JsonData RewardList = new JsonData();
            RewardList.SetJsonType(JsonType.Array);
            for (int i = 0; i < drc.Count; i++)
            {
                object[] array = drc[i].ItemArray;
                JsonData lst = new JsonData();
                lst.SetJsonType(JsonType.Array);
                for (int j = 0; j < array.Length; j++)
                {
                    lst.Add(array[j]);
                }
                RewardList.Add(lst);
            }
            drc = DBManager.Select(string.Format("select DailyRewardCount,DailyRewardState from player where Id={0}", id));
            object[] array1 = drc[0].ItemArray;
            int count = (int)array1[0];
            int state = (int)array1[1];
            JsonData other = new JsonData();
            other.SetJsonType(JsonType.Array);
            other.Add(count);
            other.Add(state);
            RewardList.Add(other);
            return GetJsonString(type, RewardList);
        }
        string OpenStoreUI(int type)//商店界面
        {
            /********************************************/
            DataRowCollection drc1 = DBManager.Select("select * from product where sort=1");
            List<object[]> objs1 = new List<object[]>();
            for (int i = 0; i < drc1.Count; i++)
            {
                object[] n = drc1[i].ItemArray;
                objs1.Add(n);
            }
            for (int i = 0; i < objs1.Count - 1; i++)
            {
                float cost_i = float.Parse(((string)objs1[i][8]).Split('/')[0]);
                for (int j = i + 1; j < objs1.Count; j++)
                {
                    float cost_j = float.Parse(((string)objs1[j][8]).Split('/')[0]);
                    if (cost_j < cost_i)
                    {
                        object[] temp = objs1[i];
                        objs1[i] = objs1[j];
                        objs1[j] = temp;
                    }
                }
            }

            List<object[]> objs2 = new List<object[]>();
            drc1 = DBManager.Select("select * from product where sort=0");
            for (int i = 0; i < drc1.Count; i++)
            {
                object[] n = drc1[i].ItemArray;
                objs2.Add(n);
            }
            for (int i = 0; i < objs2.Count - 1; i++)
            {
                float cost_i = float.Parse(((string)objs2[i][8]).Split('/')[0]);
                for (int j = i + 1; j < objs2.Count; j++)
                {
                    float cost_j = float.Parse(((string)objs2[j][8]).Split('/')[0]);
                    if (cost_j < cost_i)
                    {
                        object[] temp = objs2[i];
                        objs2[i] = objs2[j];
                        objs2[j] = temp;
                    }
                }
            }

            JsonData products = new JsonData();
            products.SetJsonType(JsonType.Array);
            for (int i = 0; i < objs1.Count; i++)
            {
                JsonData pro = new JsonData();
                pro.SetJsonType(JsonType.Array);
                for (int j = 0; j < objs1[i].Length; j++)
                {
                    pro.Add(objs1[i][j]);
                }
                products.Add(pro);
            }
            for (int i = 0; i < objs2.Count; i++)
            {
                JsonData pro = new JsonData();
                pro.SetJsonType(JsonType.Array);
                for (int j = 0; j < objs2[i].Length; j++)
                {
                    pro.Add(objs2[i][j]);
                }
                products.Add(pro);
            }
            return GetJsonString(type, products);
            /******************************************/
        }
        string OpenMoreStoreUI(int type)//更多商店界面
        {
            /********************************************/
            DataRowCollection drc1 = DBManager.Select("select * from product where sort=1");
            List<object[]> objs1 = new List<object[]>();
            for (int i = 0; i < drc1.Count; i++)
            {
                object[] n = drc1[i].ItemArray;
                objs1.Add(n);
            }
            for (int i = 0; i < objs1.Count - 1; i++)
            {
                float cost_i = float.Parse(((string)objs1[i][8]).Split('/')[0]);
                for (int j = i + 1; j < objs1.Count; j++)
                {
                    float cost_j = float.Parse(((string)objs1[j][8]).Split('/')[0]);
                    if (cost_j < cost_i)
                    {
                        object[] temp = objs1[i];
                        objs1[i] = objs1[j];
                        objs1[j] = temp;
                    }
                }
            }

            List<object[]> objs2 = new List<object[]>();
            drc1 = DBManager.Select("select * from product where sort=0");
            for (int i = 0; i < drc1.Count; i++)
            {
                object[] n = drc1[i].ItemArray;
                objs2.Add(n);
            }
            for (int i = 0; i < objs2.Count - 1; i++)
            {
                float cost_i = float.Parse(((string)objs2[i][8]).Split('/')[0]);
                for (int j = i + 1; j < objs2.Count; j++)
                {
                    float cost_j = float.Parse(((string)objs2[j][8]).Split('/')[0]);
                    if (cost_j < cost_i)
                    {
                        object[] temp = objs2[i];
                        objs2[i] = objs2[j];
                        objs2[j] = temp;
                    }
                }
            }

            JsonData products = new JsonData();
            products.SetJsonType(JsonType.Array);
            for (int i = 0; i < objs1.Count; i++)
            {
                JsonData pro = new JsonData();
                pro.SetJsonType(JsonType.Array);
                for (int j = 0; j < objs1[i].Length; j++)
                {
                    pro.Add(objs1[i][j]);
                }
                products.Add(pro);
            }
            for (int i = 0; i < objs2.Count; i++)
            {
                JsonData pro = new JsonData();
                pro.SetJsonType(JsonType.Array);
                for (int j = 0; j < objs2[i].Length; j++)
                {
                    pro.Add(objs2[i][j]);
                }
                products.Add(pro);
            }
            return GetJsonString(type, products);
            /******************************************/
            
            
        }
        string PassLevelSuccessful(JsonData data, int type) //过关
        {
            JsonData greens = data["greens"];
            int[] numbers = new int[greens.Count];
            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = (int)greens[i];
            }
            DataRowCollection drc = DBManager.Select(string.Format("select Mission,TargetCollectedNumber,Scores,Stars,CurrentLevel from player where Id={0}", id));
            string _mission = (string)drc[0][0];
            int    _collectednum = (int)drc[0][1];
            string scores = (string)drc[0][2];
            string stars = (string)drc[0][3];
            int    currentlevel = (int)drc[0][4];
            JsonData m_lst = JsonMapper.ToObject(_mission);
            if (m_lst.Count == 0)
            {
                string mmm = GetMissionList(0);
                m_lst = JsonMapper.ToObject(mmm)["msg"];
            }
            for (int i = 0; i < m_lst.Count; i++)
            {
                int ReqTypeA = 0;
                int CollectedNumA = 0;
                int ReqTypeB = 0;
                int CollectedNumB = 0;
                int ReqTypeC = 0;
                int CollectedNumC = 0;
                JsonData m = m_lst[i]["data"];
                ReqTypeA = (int)m[2];
                CollectedNumA = (int)m[4];
                ReqTypeB = (int)m[7];
                CollectedNumB = (int)m[9];
                ReqTypeC = (int)m[12];
                CollectedNumC = (int)m[14];
                if (ReqTypeA != -1)
                {
                    if(ReqTypeA==17)
                    {
                        for (int j = 6; j < 18;j++ )
                        {
                            CollectedNumA+=numbers[j];
                        }
                    }
                    else if (ReqTypeA ==23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else if (ReqTypeA == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else if (ReqTypeA == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else CollectedNumA += numbers[ReqTypeA];
                }
                if (ReqTypeB != -1)
                {
                    if (ReqTypeB == 17)
                    {
                        for (int j = 6; j < 18; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else CollectedNumB += numbers[ReqTypeB];
                }
                if (ReqTypeC != -1)
                {
                    if (ReqTypeC == 17)
                    {
                        for (int j = 6; j < 18; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else CollectedNumC += numbers[ReqTypeC];
                }
                m[4] = CollectedNumA;
                m[9] = CollectedNumB;
                m[14] = CollectedNumC;
            }
            drc = DBManager.Select("select Id,Type from currentactivity ");
            for (int i = 0; i < drc.Count;i++ )
            {
                int _aid = (int)drc[i][0];
                int _type = (int)drc[i][1];
                if (_type == 1)
                {
                    drc = DBManager.Select(string.Format("select TargetType from activity1 where Id={0}", _aid));
                    string _collecttype = (string)drc[0][0];
                    int code = a_GetTypeCode(_collecttype);
                    if (code == 5)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            _collectednum += numbers[j];
                        }
                    }
                    else if (code == 8)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            _collectednum += numbers[j];
                        }
                    }
                    else if (code == 9)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            _collectednum += numbers[j];
                        }
                    }
                    else if (code == 12)
                    {
                        for (int j = 6; j < 18; j++)
                        {
                            _collectednum += numbers[j];
                        }
                    }
                    else if (code == 0||code==1||code==2)
                    {
                        _collectednum += numbers[code];
                    }
                    else if (code == 3)
                    {
                        _collectednum += numbers[43];
                    }
                    else if (code == 4)
                    {
                        _collectednum += numbers[42];
                    }
                    else if (code == 6)
                    {
                        _collectednum += numbers[38];
                    }
                    else if (code == 7)
                    {
                        _collectednum += numbers[3];
                    }
                    else if (code == 10)
                    {
                        _collectednum += numbers[41];
                    }
                    else if (code == 11)
                    {
                        _collectednum += numbers[37];
                    }
                    else if (code == 13)
                    {
                        _collectednum += numbers[40];
                    }
                    else if (code == 14)
                    {
                        _collectednum += numbers[39];
                    }
                    else if (code == 15)
                    {
                        _collectednum += numbers[4];
                    }
                    else if (code == 16)
                    {
                        _collectednum += numbers[44];
                    }
                    else if (code == 17)
                    {
                        _collectednum += numbers[5];
                    }
                    else if (code == 18)
                    {
                        _collectednum += numbers[36];
                    }
                    break;
                }
            }
            JsonData lss = data["LSS"];
            int _CurrentLevel = (int)lss[0];
            int _Star = (int)lss[1];
            int _Score = (int)lss[2];
            JsonData st = JsonMapper.ToObject(stars);
            int OriginalStar=(int)st[_CurrentLevel-1];
            st[_CurrentLevel - 1] = _Star;
            stars = st.ToJson();
            JsonData sc = JsonMapper.ToObject(scores);
            sc[_CurrentLevel - 1] = _Score;
            scores = sc.ToJson();
            if (currentlevel == _CurrentLevel-1)
            {
                currentlevel += 1;
            }
            DBManager.Update(string.Format("update player set Mission='{0}',TargetCollectedNumber={1},Scores='{2}',Stars='{3}',CurrentLevel={4} where Id={5}", m_lst.ToJson(), _collectednum, scores, stars, currentlevel, id));
            JsonData jj = new JsonData();
            jj.SetJsonType(JsonType.Array);
            /****************************/
            drc = DBManager.Select("select LevelSuccessInfo from info");
            string info=(string)drc[0][0];
            JsonData _info = JsonMapper.ToObject(info);
            int  nums=(int)_info[_CurrentLevel - 1];
            nums += 1;
            _info[_CurrentLevel - 1] = nums;
            DBManager.Update(string.Format("update info set LevelSuccessInfo='{0}'", _info.ToJson()));
            /***************************/
            return GetJsonString(type, jj);
        }
        string PassLevelFail(JsonData data, int type) //过关失败
        {
            JsonData greens = data["greens"];
            int[] numbers = new int[greens.Count];
            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = (int)greens[i];
            }
            DataRowCollection drc = DBManager.Select(string.Format("select Mission,TargetCollectedNumber from player where Id={0}", id));
            string _mission = (string)drc[0][0];
            int _collectednum = (int)drc[0][1];
            JsonData m_lst = JsonMapper.ToObject(_mission);
            if (m_lst.Count == 0)
            {
                string mmm = GetMissionList(0);
                m_lst = JsonMapper.ToObject(mmm)["msg"];
            }
            for (int i = 0; i < m_lst.Count; i++)
            {
                int ReqTypeA = 0;
                int CollectedNumA = 0;
                int ReqTypeB = 0;
                int CollectedNumB = 0;
                int ReqTypeC = 0;
                int CollectedNumC = 0;
                JsonData m = m_lst[i]["data"];
                ReqTypeA = (int)m[2];
                CollectedNumA = (int)m[4];
                ReqTypeB = (int)m[7];
                CollectedNumB = (int)m[9];
                ReqTypeC = (int)m[12];
                CollectedNumC = (int)m[14];
                if (ReqTypeA != -1)
                {
                    if(ReqTypeA==17)
                    {
                        for (int j = 6; j < 18;j++ )
                        {
                            CollectedNumA+=numbers[j];
                        }
                    }
                    else if (ReqTypeA ==23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else if (ReqTypeA == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else if (ReqTypeA == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumA += numbers[j];
                        }
                    }
                    else CollectedNumA += numbers[ReqTypeA];
                }
                if (ReqTypeB != -1)
                {
                    if (ReqTypeB == 17)
                    {
                        for (int j = 6; j < 18; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else if (ReqTypeB == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumB += numbers[j];
                        }
                    }
                    else CollectedNumB += numbers[ReqTypeB];
                }
                if (ReqTypeC != -1)
                {
                    if (ReqTypeC == 17)
                    {
                        for (int j = 6; j < 18; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 23)
                    {
                        for (int j = 18; j < 24; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 29)
                    {
                        for (int j = 24; j < 30; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else if (ReqTypeC == 35)
                    {
                        for (int j = 30; j < 36; j++)
                        {
                            CollectedNumC += numbers[j];
                        }
                    }
                    else CollectedNumC += numbers[ReqTypeC];
                }
                m[4] = CollectedNumA;
                m[9] = CollectedNumB;
                m[14] = CollectedNumC;
            }
            DBManager.Update(string.Format("update player set Mission='{0}' where Id={1}", m_lst.ToJson(), id));
            JsonData jj = new JsonData();
            jj.SetJsonType(JsonType.Array);
            return GetJsonString(type, jj);
        }
        string LogInWithFaceBookId(JsonData jd, int type)//FaceBook登录 
        {
            
            JsonData MySelf = jd["MySelf"];
            JsonData Friends = jd["Friends"];
            /****************************************/
            for (int k = 0; k < Friends.Count; k++)
            {
                string MyFriendName = Convert.ToBase64String(Encoding.UTF8.GetBytes((string)Friends[k]["FbName"]));
                Friends[k]["FbName"] = MyFriendName;
            }
            /*******************************************/
            int    CurrentLevel = (int)jd["CurrentLevel"];
            string response = "";
            DataRowCollection drc = DBManager.Select(string.Format("select Fbid,Pid from player where id={0}", id));
            string Pid=(string)drc[0][1];
            if ((string)drc[0][0] == "None")//用这个id第一次登陆facebook
            {
                string SelfFbid = (string)MySelf["Fbid"];
                string SelfName = (string)MySelf["FbName"];
                /*****************************************/
                SelfName = Convert.ToBase64String(Encoding.UTF8.GetBytes(SelfName));
                /*****************************************/
                string SelfHead = (string)MySelf["FbHead"];
                drc = DBManager.Select(string.Format("select * from fbplayer where Fbid='{0}'", SelfFbid));
                JsonData SelfGameFriends = new JsonData();
                SelfGameFriends.SetJsonType(JsonType.Array);
                if (drc.Count == 0)//这个玩家第一次登陆Facebook
                {
                    drc = DBManager.Select("select * from fbplayer");
                    for (int i = 0; i < drc.Count; i++)
                    {
                        string _Fbid = (string)drc[i][0];
                        string _Head = (string)drc[i][1];
                        string _OtherFriends = (string)drc[i][2];
                        string _Name = (string)drc[i][3];
                        JsonData others = JsonMapper.ToObject(_OtherFriends);
                        for (int j = 0; j < others.Count; j++)
                        {
                            if (SelfFbid == (string)others[j]["Fbid"])
                            {
                                string js = "{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", _Fbid, _Name, _Head, 0, 1) + "}";
                                JsonData a = JsonMapper.ToObject(js);
                                Friend ff = new Friend(a);
                                SelfGameFriends.Add(ff.ToJsonData());
                                DataRowCollection drc1 = DBManager.Select(string.Format("select Friends from player where Fbid='{0}'", _Fbid));
                                string OthersGameFriends = (string)drc1[0][0];
                                JsonData OthersGameFriendsData = JsonMapper.ToObject(OthersGameFriends);
                                string js1 = "{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", SelfFbid, SelfName, SelfHead, 0, 1) + "}";
                                JsonData a1 = JsonMapper.ToObject(js1);
                                Friend ff1 = new Friend(a1);
                                OthersGameFriendsData.Add(ff1.ToJsonData());
                                DBManager.Update(string.Format("update player set Friends='{0}' where Fbid='{1}'", OthersGameFriendsData.ToJson(), _Fbid));
                                break;
                            }
                        }
                    }
                    DBManager.Update(string.Format("update player set Friends='{0}',Fbid='{1}',FbHead='{2}',FbName='{3}',Name='{4}' where Id={5}", SelfGameFriends.ToJson(), SelfFbid, SelfHead, SelfName, SelfName, id));
                    DBManager.Insert(string.Format("insert into fbplayer (Fbid,Head,Friends,Name) values ('{0}','{1}','{2}','{3}')", SelfFbid, SelfHead, Friends.ToJson(), SelfName));
                }
                else
                {
                    drc = DBManager.Select(string.Format("select Friends from player where Fbid='{0}'", SelfFbid));
                    string _OtherFriends = (string)drc[0][0];
                    SelfGameFriends = JsonMapper.ToObject(_OtherFriends);
                    DBManager.Update(string.Format("update player set Friends='{0}',Fbid='{1}',FbHead='{2}',FbName='{3}',Name='{4}' where Id={5}", SelfGameFriends.ToJson(), SelfFbid, SelfHead, SelfName, SelfName, id));
                    drc = DBManager.Select(string.Format("select Gold,CurrentLevel,Scores,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where Fbid='{0}'", SelfFbid));
                    object[] array = drc[0].ItemArray;
                    for (int i = 1; i < drc.Count; i++)
                    {
                        object[] array1 = drc[i].ItemArray;
                        if ((int)array1[1] > (int)array[1])
                        {
                            array = array1;
                        }
                    }
                    DBManager.Update(string.Format("update player set Gold={0},CurrentLevel={1},Scores='{2}',Stars='{3}',LineItem={4},MagicItem={5},ColorItem={6},ExchangeItem={7},HammerItem={8},CrossItem={9} where id={10}", (int)array[0], (int)array[1], (string)array[2], (string)array[3], (int)array[4], (int)array[5], (int)array[6], (int)array[7], (int)array[8], (int)array[9], id));
                }
                drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where id={0}", this.id));
                JsonData js2 = new JsonData();
                js2.SetJsonType(JsonType.Array);
                DataRow row = drc[0];
                object[] columns = row.ItemArray;
                for (int j = 0; j < columns.Length; j++)
                {
                    if (j == 14)
                    {
                        /*****************************************/
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch 
                        {
                        
                        }
                        
                        /*****************************************/
                    }

                    if (j == 6)
                    {
                        JsonData jd1 = JsonMapper.ToObject((string)columns[6]);
                        JsonData boss1 = new JsonData();
                        boss1["Stars"] = jd1;
                        js2.Add(boss1);
                    }
                    else js2.Add(columns[j]);
                }
                JsonData rank = JsonMapper.ToObject(ReadyToEnterGame(CurrentLevel, 0))["msg"];
                JsonData boss = new JsonData();
                boss["property"] = js2;
                boss["rank"] = rank;
                boss["friends"] = GetFriendsAfterLogIn();
                response = GetJsonString(type, boss);
            }
            else //当前设备下换账号登陆
            {
                int BossId = 0;
                string SelfFbid = (string)MySelf["Fbid"];
                string SelfName = (string)MySelf["FbName"];
                /*****************************************/
                SelfName = Convert.ToBase64String(Encoding.UTF8.GetBytes(SelfName));
                /*****************************************/
                string SelfHead = (string)MySelf["FbHead"];
                drc = DBManager.Select(string.Format("select * from fbplayer where Fbid='{0}'", SelfFbid));
                JsonData SelfGameFriends = new JsonData();
                SelfGameFriends.SetJsonType(JsonType.Array);
                if (drc.Count == 0)
                {
                    drc = DBManager.Select("select * from fbplayer");
                    for (int i = 0; i < drc.Count; i++)
                    {
                        string _Fbid = (string)drc[i][0];
                        string _Head = (string)drc[i][1];
                        string _OtherFriends = (string)drc[i][2];
                        string _Name = (string)drc[i][3];
                        JsonData others = JsonMapper.ToObject(_OtherFriends);
                        for (int j = 0; j < others.Count; j++)
                        {
                            if (SelfFbid == (string)others[j]["Fbid"])
                            {
                                string js = "{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", _Fbid, _Name, _Head, 0, 1) + "}";
                                JsonData a = JsonMapper.ToObject(js);
                                Friend ff = new Friend(a);
                                SelfGameFriends.Add(ff.ToJsonData());
                                DataRowCollection drc1 = DBManager.Select(string.Format("select Friends from player where Fbid='{0}'", _Fbid));
                                string OthersGameFriends = (string)drc1[0][0];
                                JsonData OthersGameFriendsData = JsonMapper.ToObject(OthersGameFriends);
                                string js1 = "{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", SelfFbid, SelfName, SelfHead, 0, 1) + "}";
                                JsonData a1 = JsonMapper.ToObject(js1);
                                Friend ff1 = new Friend(a1);
                                OthersGameFriendsData.Add(ff1.ToJsonData());
                                DBManager.Update(string.Format("update player set Friends='{0}' where Fbid='{1}'", OthersGameFriendsData.ToJson(), _Fbid));
                                break;
                            }
                        }
                      }
                    DBManager.Insert(string.Format("insert into player (Pid,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,Scores,Friends,Fbid,FbHead,FbName)  values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}') ", Pid, 0, 0, InitializeScores(), 0, 0, 0, 0, 0, 0, 0, SelfName, InitializeScores(), SelfGameFriends.ToJson(), SelfFbid, SelfHead, SelfName));
                    DBManager.Insert(string.Format("insert into fbplayer (Fbid,Head,Friends,Name) values ('{0}','{1}','{2}','{3}')", SelfFbid, SelfHead, Friends.ToJson(), SelfName));
                    drc = DBManager.Select(string.Format("select Id from player where Fbid='{0}'", SelfFbid));
                    BossId=(int)drc[0][0];
                }
                else
                {
                    drc = DBManager.Select(string.Format("select Friends,id from player where Fbid='{0}'", SelfFbid));
                    string _OtherFriends = (string)drc[0][0];
                    int _id=(int)drc[0][1];
                    SelfGameFriends = JsonMapper.ToObject(_OtherFriends);
                    DBManager.Update(string.Format("update player set Friends='{0}',Fbid='{1}',FbHead='{2}',FbName='{3}',Name='{4}' where Id={5}", SelfGameFriends.ToJson(), SelfFbid, SelfHead, SelfName, SelfName, _id));
                    drc = DBManager.Select(string.Format("select Gold,CurrentLevel,Scores,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem ,Id from player where Fbid='{0}'", SelfFbid));
                    object[] array = drc[0].ItemArray;
                    for (int i = 1; i < drc.Count; i++)
                    {
                        object[] array1 = drc[i].ItemArray;
                        if ((int)array1[1] > (int)array[1])
                        {
                            array = array1;
                        }
                    }
                    BossId = (int)array[10];
                    DBManager.Update(string.Format("update player set Gold={0},CurrentLevel={1},Scores='{2}',Stars='{3}',LineItem={4},MagicItem={5},ColorItem={6},ExchangeItem={7},HammerItem={8},CrossItem={9} where id={10}", (int)array[0], (int)array[1], (string)array[2], (string)array[3], (int)array[4], (int)array[5], (int)array[6], (int)array[7], (int)array[8], (int)array[9], BossId));
                }
                drc = DBManager.Select(string.Format("select Id,Pid,Fbid,FbHead,Gold,CurrentLevel,Stars,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem,Power,Name,PresentPowerState,DailyRewardState from player where Id={0}", BossId));
                JsonData js2 = new JsonData();
                js2.SetJsonType(JsonType.Array);
                DataRow row = drc[0];
                object[] columns = row.ItemArray;
                this.id=BossId;
                for (int j = 0; j < columns.Length; j++)
                {
                    if (j == 14)
                    {
                        try
                        {
                            columns[j] = Encoding.UTF8.GetString(Convert.FromBase64String((string)columns[j]));
                        }
                        catch
                        {

                        }
                    }
                    if (j == 6)
                    {
                        JsonData jd1 = JsonMapper.ToObject((string)columns[6]);
                        JsonData boss1 = new JsonData();
                        boss1["Stars"] = jd1;
                        js2.Add(boss1);
                    }
                    else js2.Add(columns[j]);
                }
                JsonData rank =JsonMapper.ToObject(ReadyToEnterGame(CurrentLevel,0))["msg"];
                JsonData boss = new JsonData();
                boss["property"] = js2;
                boss["rank"] = rank;
                boss["friends"] = GetFriendsAfterLogIn();
                response = GetJsonString(type, boss);
            }
            return response;
        }
        JsonData GetFriendsAfterLogIn()
        {
            DataRowCollection drc = DBManager.Select(string.Format("select Friends from player where Id={0}", id));
            string f = (string)drc[0][0];
            JsonData Friends = JsonMapper.ToObject(f);
            JsonData FirendsWithMsg = new JsonData();
            FirendsWithMsg.SetJsonType(JsonType.Array);
            for (int i = 0; i < Friends.Count; i++)
            {
                int _MsgCount = (int)Friends[i]["MsgCount"];
                if (_MsgCount != 0)
                {
                    try
                    {
                        Friends[i]["FbName"] = Encoding.UTF8.GetString(Convert.FromBase64String((string)Friends[i]["FbName"]));
                    }
                    catch 
                    {
                    
                    }
                    
                    FirendsWithMsg.Add(Friends[i]);
                }
            }
            return FirendsWithMsg;
        }
        void   WriteDataToFile(string path, string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            FileStream fs = new FileStream(path, FileMode.Open);
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();
        }
        string ReadDataFromFile(string path)
        {
            byte[] buffer1 = new byte[1024 * 4];
            FileStream fs = new FileStream(path, FileMode.Open);
            int count = fs.Read(buffer1, 0, buffer1.Length);
            byte[] buffer2 = new byte[count];
            for (int i = 0; i < count; i++)
            {
                buffer2[i] = buffer1[i];
            }
            string data = Encoding.UTF8.GetString(buffer2);
            return data;
        }
        bool   UpdatePlayerWithClientOrServer(JsonData data, object[] columns)
        {
            bool IsTreated = false;
            string Pid = (string)data[1];
            string Fbid = (string)data[2];
            int gold = (int)data[3];
            int level = (int)data[4];
            string stars = data[5]["Stars"].ToJson();
            int line = (int)data[6];
            int magic = (int)data[7];
            int color = (int)data[8];
            int exchange = (int)data[9];
            int hammer = (int)data[10];
            int cross = (int)data[11];
            int power = (int)data[12];
            string name = (string)data[13];

            int s_gold = (int)columns[4];
            int s_level = (int)columns[5];
            string s_levelinfo = (string)columns[6];
            int s_line = (int)columns[7];
            int s_magic = (int)columns[8];
            int s_color = (int)columns[9];
            int s_exchange = (int)columns[10];
            int s_hammer = (int)columns[11];
            int s_cross = (int)columns[12];
            int s_power = (int)columns[13];
            if (s_level <= level)
            {
                if (gold <= s_gold && line <= s_line && magic <= s_magic && color <= s_color && exchange <= s_exchange && hammer <= s_hammer && cross <= s_cross)
                {
                    //用本地数据覆盖服务器数据
                    DBManager.Update(string.Format("update player set Gold={0},CurrentLevel={1},Stars='{2}',LineItem={3},MagicItem={4},ColorItem={5},ExchangeItem={6},HammerItem={7},CrossItem={8},Power={9},Name='{10}' where Id={11}", gold, level, stars, line, magic, color, exchange, hammer, cross, power, name, this.id));
                }
                else IsTreated = true;
            }
            return IsTreated;
        }
        string GetMissionList(int type)//获取任务列表 
        {
            DataRowCollection drc = DBManager.Select(string.Format("select Mission,CurrentMissionStep from player where id={0}", id));
            string lst = (string)drc[0][0];
            int CurrentMissionStep = (int)drc[0][1];
            /******************/
            JsonData jd = JsonMapper.ToObject(lst);
            if (jd.Count == 0)
            {
                if(CurrentMissionStep!=0&&CurrentMissionStep<21)
                {
                    DataRowCollection drc10 = DBManager.Select("select MissionInfo from info");
                   JsonData m_info = JsonMapper.ToObject((string)drc10[0][0]);
                   int compnum=(int)m_info[CurrentMissionStep-1];
                   compnum += 1;
                   m_info[CurrentMissionStep - 1]=compnum;
                   DBManager.Update(string.Format("update info set MissionInfo='{0}'", m_info.ToJson()));
                }
                jd = new JsonData();
                jd.SetJsonType(JsonType.Array);
                if (CurrentMissionStep < 21)
                {
                    CurrentMissionStep += 1;
                }
                drc = DBManager.Select(string.Format("select * from mission where Step={0}", CurrentMissionStep));
                for (int i = 0; i < drc.Count; i++)
                {
                    JsonData data = new JsonData();
                    JsonData SmallMission = new JsonData();
                    SmallMission.SetJsonType(JsonType.Array);
                    object[] array = drc[i].ItemArray;
                    object[] NewArray = new object[array.Length + 3];
                    int index = 0;
                    for (int k = 0; k < array.Length; k++)
                    {
                        NewArray[index] = array[k];
                        if (k == 3 || k == 7 || k == 11)
                        {
                            index += 1;
                            NewArray[index] =0;
                        }
                        index++;
                    }
                    for (int j = 0; j < NewArray.Length; j++)
                    {
                        if(j==2||j==7||j==12)
                        {
                            int code1 = m_GetTypeCode((string)NewArray[j]);
                            NewArray[j] = code1;
                        }
                        else if(j==5||j==10||j==15)
                        {
                            int code2 = m_GetTypeCode((string)NewArray[j]);
                            NewArray[j] = code2;
                        }
                        SmallMission.Add(NewArray[j]);
                    }
                    data["data"] = SmallMission;
                    jd.Add(data);
                }
                DBManager.Update(string.Format("update player set Mission='{0}',CurrentMissionStep={1} where id={2}", jd.ToJson(), CurrentMissionStep, id));
            }
            return GetJsonString(type, jd);
        }
        string GetMissionReward(JsonData data, int type)//完成一个任务(点击complete按钮) 
        {
            JsonData CurrentMission = null;
            JsonData m_array = data["data"];
            DataRowCollection drc = DBManager.Select(string.Format("select Mission from player where id={0}", id));
            string lst = (string)drc[0][0];
            JsonData MissionList = JsonMapper.ToObject(lst);
            List<JsonData> m_lst = new List<JsonData>();
            for (int i = 0; i < MissionList.Count; i++)
            {
                m_lst.Add(MissionList[i]);
            }
            /************************/
            int m_id = (int)m_array[1];
            int RewarTypeA = (int)m_array[5];
            int RewarNumberA = (int)m_array[6];
            int RewarTypeB = (int)m_array[10];
            int RewarNumberB = (int)m_array[11];
            int RewarTypeC = (int)m_array[15];
            int RewarNumberC = (int)m_array[16];
            for (int i = 0; i < m_lst.Count; i++)
            {
                if (m_id == (int)m_lst[i]["data"][1])
                {
                    CurrentMission = m_lst[i];
                    break;
                }
            }
            List<string> TypeNames = new List<string>();
            List<int> Numbers = new List<int>();
            string NameA = GetStringName1(RewarTypeA);
            string NameB = GetStringName1(RewarTypeB);
            string NameC = GetStringName1(RewarTypeC);
            if (NameA != null)
            {
                TypeNames.Add(NameA);
                Numbers.Add(RewarNumberA);
            }
            if (NameB != null)
            {
                TypeNames.Add(NameB);
                Numbers.Add(RewarNumberB);
            }
            if (NameC != null)
            {
                TypeNames.Add(NameC);
                Numbers.Add(RewarNumberC);
            }
            string CmdText = "select ";
            for (int i = 0; i < TypeNames.Count; i++)
            {
                CmdText += TypeNames[i];
                if (i != TypeNames.Count - 1)
                {
                    CmdText += ",";
                }
            }
            CmdText += string.Format(" from player where Id={0}", id);
            drc = DBManager.Select(CmdText);
            object[] array = drc[0].ItemArray;
            CmdText = "update player set ";
            for (int i = 0; i < array.Length; i++)
            {
                int number = (int)array[i] + Numbers[i];
                CmdText += string.Format("{0}={1}", TypeNames[i], number);
                if (i != array.Length - 1)
                {
                    CmdText += ",";
                }
            }
            CmdText += string.Format(" where Id={0}", id);
            DBManager.Update(CmdText);
            m_lst.Remove(CurrentMission);
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            for (int i = 0; i < m_lst.Count; i++)
            {
                jd.Add(m_lst[i]);
            }
            MissionList = jd;
            DBManager.Update(string.Format("update player set Mission='{0}' where id={1}", MissionList.ToJson(), id));
            if (m_lst.Count == 0)
            {
                MissionList = JsonMapper.ToObject(GetMissionList(0))["msg"];
            }
            drc = DBManager.Select(string.Format("select Gold,LineItem,MagicItem,ColorItem,ExchangeItem,HammerItem,CrossItem from player where id={0}", id));
            JsonData property = new JsonData();
            property.SetJsonType(JsonType.Array);
            object[] objs = drc[0].ItemArray;
            for (int i = 0; i < objs.Length; i++)
            {
                property.Add(objs[i]);
            }
            /**************************/
            JsonData boss = new JsonData();
            boss["CurrentMission"] = data;
            boss["MissionList"] = MissionList;
            boss["Property"] = property;
            return GetJsonString(type, boss);
        }
        string GetStringName1(int RewardType) //名字转换函数1
        {
            /****0-7
            魔力   
	        金币 
	        染色
	        直线
	        交换
	        小锤
	        十字
            ******/
            string ItemName = null;
            switch (RewardType)
            {
                case 0:
                    ItemName = "MagicItem";
                    break;
                case 1:
                    ItemName = "Gold";
                    break;
                case 2:
                    ItemName = "ColorItem";
                    break;
                case 3:
                    ItemName = "LineItem";
                    break;
                case 4:
                    ItemName = "ExchangeItem";
                    break;
                case 5:
                    ItemName = "HammerItem";
                    break;
                case 6:
                    ItemName = "CrossItem";
                    break;
            }

            return ItemName;
        }
        string GetStringName2(int ItemId) //名字转换函数2
        {
            /****0-7
            魔力   
	        金币 
	        染色
	        直线
	        交换
	        小锤
	        十字
            ******/
            string ItemName = null;
            switch (ItemId)
            {
                case 1:
                    ItemName = "CrossItem";
                    break;
                case 2:
                    ItemName = "ExchangeItem";
                    break;
                case 3:
                    ItemName = "HammerItem";
                    break;
                case 4:
                    ItemName = "ColorItem";
                    break;
                case 5:
                    ItemName = "LineItem";
                    break;
                case 6:
                    ItemName = "MagicItem";
                    break;
            }
            return ItemName;
        }
        string GetItemCostList(int ItemId, int type) //获取道具价格及优惠表
        {
            DataRowCollection drc = DBManager.Select("select * from itemcost ");
            int[] Count = new int[drc.Count];
            int[] Cost = new int[drc.Count];
            int[] Discount = new int[drc.Count];
            for (int i = 0; i < drc.Count; i++)
            {
                object[] array = drc[i].ItemArray;
                Count[i] = (int)array[0];
                string s = (string)array[GetIndex(ItemId)];
                string[] t = s.Split('/');
                int cost = int.Parse(t[0]);
                int discount = int.Parse(t[1]);
                Cost[i] = cost;
                Discount[i] = discount;
            }
            JsonData jd = new JsonData();
            if(ItemId==4)
            {
                ItemId = 5;
            }
            else if(ItemId==5)
            {
                ItemId = 4;
            }
            jd["Id"] = ItemId;
            JsonData CountArray = new JsonData();
            CountArray.SetJsonType(JsonType.Array);
            for (int i = 0; i < Count.Length; i++)
            {
                CountArray.Add(Count[i]);
            }
            jd["Count"] = CountArray;
            JsonData CostArray = new JsonData();
            CostArray.SetJsonType(JsonType.Array);
            for (int i = 0; i < Cost.Length; i++)
            {
                CostArray.Add(Cost[i]);
            }
            jd["Cost"] = CostArray;
            JsonData DiscountArray = new JsonData();
            DiscountArray.SetJsonType(JsonType.Array);
            for (int i = 0; i < Discount.Length; i++)
            {
                DiscountArray.Add(Discount[i]);
            }
            jd["Discount"] = DiscountArray;
            return GetJsonString(type, jd);
        }
        int GetIndex(int ItemId) 
        {
            int index = 0;
         switch(ItemId)
         {
             case 1:
                 index = 6;
                 break;
             case 2:
                 index = 4;
                 break;
             case 3:
                 index = 5;
                 break;
             case 4:
                 index = 1;
                 break;
             case 5:
                 index = 3;
                 break;
             case 6:
                 index = 2;
                 break;
         }

         return index;
        }
        string BuyOneItem(JsonData data, int type) //购买一个道具
        {
            JsonData boss = new JsonData();
            int flag=0;
            int ItemId = (int)data[0];
            int ItemCount = (int)data[1];
            int UsedGold = (int)data[2];
            string ItemName = GetStringName2(ItemId);
            DataRowCollection drc = DBManager.Select(string.Format("select {0},Gold from player where Id={1} ", ItemName, id));
            object[] array = drc[0].ItemArray;
            int count = (int)array[0];
            int Orig = count;
            int gold = (int)array[1];
            if (gold >= UsedGold)
            {
                flag=1;
                count += ItemCount;
                gold -= UsedGold;
                DBManager.Update(string.Format("update player set {0}={1},Gold={2} where Id={3} ", ItemName, count, gold, id));
                JsonData jd = new JsonData();
                jd.SetJsonType(JsonType.Array);
                jd.Add(ItemName);
                jd.Add(ItemId);
                jd.Add(count);
                jd.Add(gold);
                jd.Add(UsedGold);
                jd.Add(count-Orig);
                boss["data"] = jd;
            }
            boss["flag"] = flag;
            return GetJsonString(type, boss);
        }
        string ChooseMapUI(int type)
        {
            JsonData jd = new JsonData();
            jd.SetJsonType(JsonType.Array);
            return GetJsonString(type, jd);
        }
        string GetJsonString(int id, JsonData msg) //获取json响应
        {
            JsonData jd = new JsonData();
            jd["type"] = id;
            jd["msg"] = msg;
            return jd.ToJson();
        }
        int    m_GetTypeCode(string name)//获取任务元素的编号
        {
            int num = -1;
            switch(name)
            {
                case "苹果":
                    num = 0;
                    break;
                case "蓝莓":
                    num = 1;
                    break;
                case "萝卜":
                    num = 2;
                    break;
                case "茄子":
                    num = 3;
                    break;
                case "梨":
                    num = 4;
                    break;
                case "西红柿":
                    num = 5;
                    break;
                case "直线特效"://(6-17)
                    num = 17;
                    break;
                case "爆炸特效"://(18-23)
                    num = 23;
                    break;
                case "染色块"://(24-29)
                    num = 29;
                    break;
                case "礼物盒"://(30,35)
                    num = 35;
                    break;
                case "水桶":
                    num = 36;
                    break;
                case "铁桶":
                    num = 37;
                    break;
                case "鸡蛋":
                    num = 38;
                    break;
                case "栗子":
                    num = 39;
                    break;
                case "魔力块":
                    num = 40;
                    break;
                case "冰块":
                    num = 41;
                    break;
                case "琥珀":
                    num = 42;
                    break;
                case "奖励障碍":
                    num = 43;
                    break;
                case "锁链障碍":
                    num = 44;
                    break;
                case "毛绒动物":
                    num = 45;
                    break;
                case "魔力":
                    num = 0;
                    break;
                case "金币":
                    num = 1;
                    break;
                case "染色":
                    num = 2;
                    break;
                case "直线":
                    num = 3;
                    break;
                case "手":
                    num = 4;
                    break;
                case "铲子":
                    num = 5;
                    break;
                case "火箭":
                    num = 6;
                    break;
            }
            return num;
        }
        int    a_GetTypeCode(string name)//获取活动元素的编号
        {
            int num = -1;
            switch (name)
            {
                case "苹果":
                    num = 0;
                    break;
                case "蓝莓":
                    num = 1;
                    break;
                case "萝卜":
                    num = 2;
                    break;
                case "奖励障碍":
                    num = 3;
                    break;
                case "琥珀":
                    num = 4;
                    break;
                case "染色块"://(24-29)
                    num = 5;
                    break;
                case "鸡蛋":
                    num = 6;
                    break;
                case "茄子":
                    num = 7;
                    break;
                case "爆炸特效"://(18-23)
                    num = 8;
                    break;
                case "礼物盒"://(30,35)
                    num = 9;
                    break;
                case "冰块":
                    num = 10;
                    break;
                case "铁桶":
                    num = 11;
                    break;
                case "直线特效"://(6-17)
                    num = 12;
                    break;
                case "魔力块":
                    num = 13;
                    break;
                case "栗子":
                    num = 14;
                    break;
                case "梨":
                    num = 15;
                    break;
                case "锁链障碍":
                    num = 16;
                    break;
                case "西红柿":
                    num = 17;
                    break;
                case "水桶":
                    num = 18;
                    break;
                case "魔力":
                    num = 4;
                    break;
                case "金币":
                    num = 0;
                    break;
                case "染色":
                    num = 2;
                    break;
                case "直线":
                    num = 3;
                    break;
                case "手":
                    num = 5;
                    break;
                case "铲子":
                    num = 6;
                    break;
                case "火箭":
                    num = 1;
                    break;
            }
            return num;
        }
    }
    public struct Friend
    {
        public string Fbid;//记录Fbid
        public string FbName;//记录名字
        public string FbHead;//记录头像连接地址
        public int MsgCount;//当前朋友发给本地玩家的消息数量
        public int CheckState;//新消息被查看标记(1,有；0，无)
        public int Score;
        public Friend(JsonData jd)
        {
            Fbid = (string)jd["Fbid"];
            FbName = (string)jd["FbName"];
            FbHead = (string)jd["FbHead"];
            MsgCount = (int)jd["MsgCount"];
            CheckState = 1;
            Score = 0;
        }
        public JsonData ToJsonData()
        {
            string js = "{" + string.Format("'Fbid':'{0}','FbName':'{1}','FbHead':'{2}','MsgCount':{3},'CheckState':{4}", Fbid, FbName, FbHead, MsgCount, CheckState) + "}";
            return JsonMapper.ToObject(js);
        }
    }
    public struct Product
    {
        public int Id;//商品id
        public string Name;//商品名
        public float Cost;//商品价格
        public int Sort;//商品的类别
        public int Count;//商品总数
        public Product(int _Id, string _Name, float _Cost, int _Sort, int _Count)
        {
            Id = _Id;
            Name = _Name;
            Cost = _Cost;
            Sort = _Sort;
            Count = _Count;
        }
    }
}
/***
1. 每一关玩家成功进入的总人数
2. 每一关所有玩家总胜利的次数
3. 玩家再次挑战某一关时之前此关的星级数（此关之前已经成功)：
 获得0星的人次、获得1星的人次、获得2星的人次、获得3星的人次
4. 每个道具的使用成功次数：
  铁锹、交换、十字、横向、魔力、染色
5. 每一关玩家成功购买步数或者时间的成功次数
6. 每一关玩家成功观看视频的次数
7. 每个商店内的产品的购买成功次数
8. 充值类活动参与成功的次数
9. 收集类活动玩家的总人数和完成的人数
10.每个任务完成的玩家数
****/

